//
//  HNDistributionAddStudent.m
//  优学荟管理系统
//
//  Created by edz on 2017/12/13.
//  Copyright © 2017年 星道三好. All rights reserved.
//

#import "HNDistributionAddStudent.h"
#import "HNDistributionStudentModel.h"
#import "HNDistributionAddStudentCell.h"

@interface HNDistributionAddStudent ()<UITableViewDelegate, UITableViewDataSource>
{
    __weak IBOutlet UIView *_HideView;
    __weak IBOutlet UIActivityIndicatorView *_Activity;
    __weak IBOutlet UIButton *_Select;
    __weak IBOutlet UILabel *_Num;
    __weak IBOutlet UITableView *_TableView;
    __weak IBOutlet UIButton *_Sure;
}
/** 数据存放地 */
@property (nonatomic, strong) NSMutableArray *DataArr;
@end

@implementation HNDistributionAddStudent

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self.navigationController.navigationBar setBackgroundImage:[LLTools createImageWithColor:ColorRGB(255, 255, 255)] forBarMetrics:(UIBarMetricsDefault)];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:ColorRGB(51,51,51)}];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:ColorRGB(255,255,255)}];
    [self.navigationController.navigationBar setBackgroundImage:[LLTools createImageWithColor:ColorRGB(47, 204, 138)] forBarMetrics:(UIBarMetricsDefault)];;

}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.title = @"新增学生";
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTargat:self action:@selector(Pop) image:@"icon_back_student_sign" highImage:@"icon_back_student_sign"];
    
    // 监控数量的变化去设置提交的状态
    [_Num addObserver:self forKeyPath:@"text" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context:nil];
    
    [_TableView registerNib:[UINib nibWithNibName:[HNDistributionAddStudentCell description] bundle:nil] forCellReuseIdentifier:@"Cell"];
    _TableView.tableFooterView = [UIView new];
    _TableView.tableHeaderView = [UIView new];
    _TableView.rowHeight = 60;
    
    [self RefreshData];
}

#pragma mark - 网络
/** 获取当前页面数据 */
- (void)RefreshData {
    
   
    NSDictionary *Params;
    if (self.isUp) {
        
     Params   = @{
                                 @"action":@"getNotAllotStudentList",
                                 @"teacherUid":self.Uid,
                                 @"lessonId":self.LessonID
                                 };
        
    }else{
        
    Params = @{
                                 @"action":@"getNotAllotChildList",
                                 @"parentUid":self.Uid,
                                 @"lessonId":self.LessonID
                                 };
    }
    
    
    
   
    [NetManager Get:LLBaseURL(@"trainLesson.do") Auth:YES Params:Params Success:^(id responseObj) {

        // 数据处理
        if ([responseObj[@"code"] isEqualToNumber:@1000]) {
            
            [_HideView removeFromSuperview];
            // 拿到数据
            NSArray *Arr = responseObj[@"t"][@"dataList"];
                // 终于有数据啦
                [Arr enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    // 处理模型转对象
                    HNDistributionStudentModel *Model = [[HNDistributionStudentModel alloc] init_ValuForKeyWithDict:obj];
                    [self.DataArr addObject:Model];
                }];
            [_TableView reloadData];
        } else {
            [_Activity stopAnimating];
            // 数据获取失败
            [SVProgressHUD showErrorWithStatus:responseObj[@"msg"]];
        }
    } Fail:^(NSError *error) {
        
        [_Activity stopAnimating];
        [SVProgressHUD showErrorWithStatus:NetErr];
    }];
}

/** 请求添加学生 */
- (void)RefreshDataOfSureWithCallBack:(void (^)())CallBack {
    
    [HUD showHUD];
    // 获取学生的id
    NSMutableArray *Arr = [NSMutableArray array];
    [self.DataArr enumerateObjectsUsingBlock:^(HNDistributionStudentModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.Selected ? [Arr addObject:[obj.uid stringValue]] : nil;
    }];
    
    NSDictionary *Params;
   
    if (self.isUp) {
      Params  = @{
                                 @"action"      :@"submitTeacherStudent",
                                 @"teacherUid"   :self.Uid,
                                 @"lessonId"    :self.LessonID,
                                 @"studentUids"   :[Arr componentsJoinedByString:@","]
                                 };
    }else{
        
        Params  = @{
                    @"action"      :@"submitParentChild",
                    @"parentUid"   :self.Uid,
                    @"lessonId"    :self.LessonID,
                    @"childUids"   :[Arr componentsJoinedByString:@","]
                    };
        
    }
    
    
    
    
   
    [NetManager Post:LLBaseURL(@"trainLesson.do") Auth:YES Params:Params Success:^(id Obj) {
        if ([Obj[@"code"] isEqualToNumber:@1000]) {
            
            [HUD showSuccess:@"学生新增加成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                CallBack ? CallBack() : nil;
            });
        } else {
            [HUD showError:Obj[@"msg"]];
        }
    } Fail:^(NSError *Error) {
        [HUD showError:NetErr];
    }];
}

#pragma mark - tableView代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.DataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HNDistributionStudentModel *Model = self.DataArr[indexPath.row];
    HNDistributionAddStudentCell *Cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    Cell.Model = Model;
    Cell.ClickSelect = ^(HNDistributionStudentModel *Model) {
        [self ClickSelect:Model IndexPath:indexPath];
    };
    return Cell;
}

#pragma mark - mark - Func
// 单选
- (void)ClickSelect:(HNDistributionStudentModel *)Model IndexPath:(NSIndexPath *)IndexPath {
    
    // 设置选中的按钮状态
    Model.Selected = !Model.Selected;
    // 计算选中人数
    NSInteger Index = [_Num.text integerValue];
    Index = Model.Selected ? Index + 1 : Index - 1;
    _Num.text = [@(Index) stringValue];
    // 判断要不要将全选状态取消
    _Select.selected = Index == self.DataArr.count ? YES:NO;
    // 刷新列表
    [_TableView reloadRowsAtIndexPaths:@[IndexPath] withRowAnimation:(UITableViewRowAnimationAutomatic)];
}

// 设置是否可以提交
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    
    _Sure.enabled = [[change valueForKey:@"new"] integerValue];
    _Sure.selected = _Sure.enabled;
}

#pragma mark - Action
- (void)Pop {
    
    [self.navigationController popViewControllerAnimated:YES];
}

/** 全选 */
- (IBAction)AllSelect:(UIButton *)Button {
    
    Button.selected = !Button.selected;
    [self.DataArr enumerateObjectsUsingBlock:^(HNDistributionStudentModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        obj.Selected = Button.selected;
    }];
    _Num.text = Button.selected ? [@(self.DataArr.count) stringValue]:@"0";
    [_TableView reloadData];
}

- (IBAction)Sure:(UIButton *)sender {
    
    [self RefreshDataOfSureWithCallBack:^{
        self.PopRefresh ? self.PopRefresh() : nil;
        [self Pop];
    }];
}

#pragma mark - Get
- (NSMutableArray *)DataArr {
    if (!_DataArr) {
        _DataArr = [NSMutableArray array];
    }
    return _DataArr;
}

@end
